#include "bsp_flash.h"
#include "boot.h"
#include "variable.h"
#include <stdlib.h>
#include <math.h>


uint32_t flashOffset=0;

// 擦除所有APP程序
void FLASH_EraseApp(void)
{
	FLASH_Unlock_Fast();
	uint64_t size = (0x08010000 - APP_ADDRESS)/0x7F;
	for(uint16_t i=0;i<size;i++)
	{
		FLASH_ErasePage_Fast(APP_ADDRESS + 0x7F*i);
	}
  FLASH_Lock_Fast();	
}

// U8转U32,快速存入
int U8toU32(uint32_t *Buf32,uint8_t *Buf8,int len)
{
	uint16_t i;
	uint16_t lastSize;
	int num32 = len/4;

	for(i=0; i<num32; )
	{
		Buf32[i] = ((uint32_t)Buf8[4*i+3]<<24) | ((uint32_t)Buf8[4*i+2]<<16) | ((uint32_t)Buf8[4*i+1]<<8) | ((uint32_t)Buf8[4*i]);
		i++;
	}
	// 不够4字节的
	lastSize = len%4;
	if(lastSize>0)
	{
		if(lastSize==1)       	Buf32[i] = ((uint32_t)Buf8[4*i]) | 0xffffff00;
		else if(lastSize==2)    Buf32[i] = (((uint32_t)Buf8[4*i+1]<<8) | ((uint32_t)Buf8[4*i])) | 0xffff0000;
		else if(lastSize==3)    Buf32[i] = ((((uint32_t)Buf8[4*i+2])<<16) | ((uint32_t)Buf8[4*i+1]<<8)  | ((uint32_t)Buf8[4*i])) | 0xff000000;
		return i+1;
	}
	else return i;
}


// 数据保存
void Flash_writeBuf(uint32_t Address, uint32_t *buf, int len)
{
	FLASH_Unlock_Fast();
	for(int i=0;i<len;i++)
	{
		FLASH_ProgramWord(Address+i*4, buf[i]);
	}
  FLASH_Lock_Fast();	
}


// 保存更新标志
void Flash_writeFlag(uint16_t ver)
{
	FLASH_Unlock_Fast();
	FLASH_ErasePage_Fast(FLAG_ADDRESS);
	FLASH_ProgramHalfWord(FLAG_ADDRESS, ver);
  FLASH_Lock_Fast();	
}

// 获取更新标志
uint16_t Flash_readFlag(void)
{
	return *(u16*)(FLAG_ADDRESS);
}


// 保存版本信息
void Flash_writeVersion(uint16_t ver)
{
	FLASH_Unlock_Fast();
	FLASH_ErasePage_Fast(VERSION_ADDRESS);
	FLASH_ProgramHalfWord(VERSION_ADDRESS, ver);
  FLASH_Lock_Fast();	
}

// 获取版本信息
uint16_t Flash_readVersion(void)
{
	return *(u16*)(VERSION_ADDRESS);
}



void getAllParam(void)
{
	LocalVersion = Flash_readVersion();  
	if(LocalVersion == 0xFFFF)  LocalVersion=0;	
	appFlag = Flash_readFlag();
	if(appFlag == 0xFFFF)  appFlag=UPDATE_ENPTY;	
}


